package com.cheche.dn;


import com.cheche.dn.error.ErrorCode;
import com.google.common.collect.Maps;

import java.io.Serializable;
import java.util.Map;

/**
 * rest通用结果对象
 * Created by cheshun on 14-8-13.
 */
public class Result implements Serializable {

	private static final long serialVersionUID = -7575718252772300092L;
	private static final int SUCCESS = 20000;
	private static final String DEFAULT_MSG = "success";

	/**
	 * 状态码
	 */
	private int code = SUCCESS;

	/**
	 * 数据对象
	 */
	private Map<String, Object> resp;

	/**
	 * 状态信息
	 */
	private String msg;

	/**
	 * 封装结果对象
	 * @param code 状态码
	 * @param msg 状态信息
	 * @param resp 待封装结果对象
	 */
	private Result(int code, String msg, Map<String, Object> resp) {
		this.code = code;
		this.resp = resp;
		this.msg = msg;
	}

	public static Result success(String key, Object value) {
		Map<String, Object> resp = Maps.newHashMap();
		resp.put(key, value);
		return new Result(SUCCESS, DEFAULT_MSG, resp);
	}

	public static Result success(String msg) {
		return new Result(SUCCESS, msg, null);
	}

	public static Result success(Map<String, Object> resp) {
		if (resp == null) {
			resp = Maps.newHashMap();
		}
		return new Result(SUCCESS, DEFAULT_MSG, resp);
	}

	public static Result success() {
		return new Result(SUCCESS, DEFAULT_MSG, null);
	}

	public Result append(String key, Object value) {
		if (resp == null) {
			resp = Maps.newHashMap();
		}
		resp.put(key, value);
		return this;
	}

	public static Result error(String msg) {
		return new Result(ErrorCode.ERROR.getValue(), msg, null);
	}

	public static Result error(ErrorCode code) {
		return new Result(code.getValue(), code.getMsg(), null);
	}

    public static Result error(ErrorCode code, String msg) {
        return new Result(code.getValue(), msg, null);
    }

	public int getCode() {
		return code;
	}

	public Map<String, Object> getResp() {
		return resp;
	}

	public String getMsg() {
		return msg;
	}

}
